package com.mall.common.domain.handler;

import com.mall.common.core.domain.Result;
import com.mall.common.domain.exceptions.BizException;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;


@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    /**
     * 业务异常处理器
     * @return
     */
    @ExceptionHandler(BizException.class)
    public Result bizExceptionHandler(BizException bizException) {
        log.error("业务异常，异常信息：{}", bizException.getMessage());
        return Result.error(bizException.getMessage());
    }

    /**
     * 处理参数不合法异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException methodArgumentNotValidException) {
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        List<String> errMessages = new ArrayList<>();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            allErrors.forEach(objectError -> {
                errMessages.add(objectError.getDefaultMessage());
            });
        }
        return Result.error(String.join(",", errMessages));
    }


}
